package util;

import com.github.junrar.Archive;
import com.github.junrar.rarfile.FileHeader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import org.apache.commons.compress.archivers.sevenz.SevenZArchiveEntry;
import org.apache.commons.compress.archivers.sevenz.SevenZFile;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;

public class ZipTool {

  /**
   * @param orgPath 源压缩文件地址
   * @param tarpath 解压后存放的目录地址
   * @author kxl
   */
  public static void apache7ZDecomp(String orgPath, String tarpath) {

    try {
      SevenZFile sevenZFile = new SevenZFile(new File(orgPath));
      SevenZArchiveEntry entry = sevenZFile.getNextEntry();
      while (entry != null) {

        // System.out.println(entry.getName());
        if (entry.isDirectory()) {

          entry = sevenZFile.getNextEntry();
          continue;
        }

        entry = sevenZFile.getNextEntry();
      }
      sevenZFile.close();
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }


  public static void unZip(File zipFile, String outDir) throws IOException {

    ZipFile zip = new ZipFile(zipFile);
    for (Enumeration enumeration = zip.getEntries(); enumeration.hasMoreElements(); ) {
      ZipEntry entry = (ZipEntry) enumeration.nextElement();
      String zipEntryName = entry.getName();
      InputStream in = zip.getInputStream(entry);

      if (entry.isDirectory()) {      //处理压缩文件包含文件夹的情况

        continue;
      }


    }
  }

  public static void unRar(String filePath) throws Exception {
    Archive archive = new Archive(new FileInputStream(filePath));
    FileHeader fileHeader = archive.nextFileHeader();
    while (fileHeader != null) {
      if (fileHeader.isDirectory()) {
        fileHeader = archive.nextFileHeader();
        continue;
      } else {
        System.out.println(fileHeader.getFileNameString());
        fileHeader = archive.nextFileHeader();
      }
    }
    archive.close();
  }

  public static void UNTar(String filePath) {
    TarArchiveInputStream tais = null;
    try {
      tais = new TarArchiveInputStream(new FileInputStream(filePath));
      TarArchiveEntry tae = null;

      while ((tae = tais.getNextTarEntry()) != null) {
        if (tae.isDirectory()) {

        } else {
          System.out.println(tae.getName());
        }
      }
      tais.close();

    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

}
